<template>
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" status-icon label-width="120px" class="demo-ruleForm">
        <el-form-item label="图片连接" prop="link">
            <el-input v-model="ruleForm.link" autocomplete="off" />
        </el-form-item>

        <el-form-item label="图片提示" prop="alt">
            <el-input v-model="ruleForm.alt" autocomplete="off" />
        </el-form-item>

        <el-form-item label="图片地址" prop="img">
            <el-input v-model.number="ruleForm.img" />
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">添加</el-button>
            <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
        </el-form-item>

    </el-form>
</template>

<script setup lang="ts">

import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus';
import { addBannerApi } from '../../../api/banner';

interface IEmits{
    (e:"ok"):void
}

const emit =defineEmits<IEmits>()

const ruleFormRef = ref<FormInstance>()

const ruleForm = reactive({
    link: '',
    alt: '',
    img: '',
})

// 表单验证
const rules = reactive<FormRules>({
    link: [
        { required: true, message: 'Please input 图片连接', trigger: 'blur' },
        { min: 3, max: 50, message: 'Length should be 3 to 50', trigger: 'blur' }
    ],
    alt: [
        { required: true, message: 'Please input 图片提示', trigger: 'blur' }],
    img: [{ required: true, message: 'Please input 图片地址', trigger: 'blur' }],
})

// 提交表单
const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return

    formEl.validate((valid:any, fields:any) => {
        if (valid) {
                addBannerApi({ ...ruleForm })
                .then((res: any) => {
                    if (res.data.code === "200") {
                        alert("添加成功！");
                        emit("ok");
                    }
                })
        } else {
            console.log('error submit!', fields)
        }
    })




}


const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
</script>

<style></style>